//
//  MNDFastPayViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/5/10.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDFastPayViewController.h"
#import "MNDBankModel.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MNDBankCardViewController.h"
#import "MNDBindBankcardViewController.h"
#import "MNDRechargeAlertViewController.h"
#import "MNDWebViewController.h"
#import "MNDBaofuBankModel.h"
#import "MNDBaofuBindCardViewController.h"
#import "MNDRechargeWebViewController.h"
#import "BaseNaviViewController.h"
#import "MNDBaofuBankListViewController.h"
#import "MNDRechargeSMSViewController.h"
#import "MNDOpenDeposAlertViewController.h"
#import "MNDDepositAlertViewController.h"
#import "MNDOpenDepositoryViewController.h"
#import "MNDOpenDepositoryPaymentViewController.h"
#import "MNDDepositWebViewController.h"
#import "MNDOpenTermsAuthViewController.h"

@interface MNDFastPayViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *bankLogoImageView;

@property (weak, nonatomic) IBOutlet UILabel *bankLabel;
@property (weak, nonatomic) IBOutlet UILabel *bankcardLabel;
@property (weak, nonatomic) IBOutlet UIButton *bindCardBtn;
@property (weak, nonatomic) IBOutlet UIButton *bankDetailBtn;

@property (weak, nonatomic) IBOutlet UITextField *rechargeMoneyTextField;
@property (weak, nonatomic) IBOutlet UILabel *userBalanceLabel;

/*! 限额说明的弹窗 */
@property (weak, nonatomic) MNDRechargeAlertViewController *alertVC;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *cardNoConstraint;


@end

@implementation MNDFastPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.bankDetailBtn setEnabled:NO];
    [self.bindCardBtn setHidden:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toFinanceVC:) name:@"recharge_to_finance" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(backToRootVC:) name:@"recharge_back" object:nil];
    
    [self initialBarbuttonItems];
}

- (void)initialBarbuttonItems {
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"限额说明"
                                                             style:UIBarButtonItemStylePlain
                                                            target:self
                                                            action:@selector(toQuotaViewVC)];
    [item setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size:14.0]} forState:UIControlStateNormal];
    [item setTintColor:kColorBlack];
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

- (void)initialLeftBarButtons {
    UIImage *backImage = [UIImage imageNamed:@"navi_back_btn_black"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(backAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:[UIColor whiteColor]];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

- (void)toFinanceVC:(NSNotification *)notification {

    [self.tabBarController setSelectedIndex:1];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)backToRootVC:(NSNotification *)notification {
    
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)backAction:(id)sender {
    UIViewController *viewController = self.navigationController.viewControllers[self.fromIndexVC];
    [self.navigationController popToViewController:viewController animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadBankInfo];
}

- (void)loadBankInfo {
    
    WeakSelf(self);
    [NetworkProgressHUD showHud];
    
    [APIManager sendRequestWithPath:API_GET_BANK_ACCOUNT parameters:[MNDSign signedParam] method:kXMHTTPMethodGET onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            dispatch_async(dispatch_get_main_queue(), ^{
                weakself.bankModel = [MNDBankModel mj_objectWithKeyValues:responseModel.data];
                [weakself configBankInfo];
            });
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
                
            } else {
                [NetworkProgressHUD showHudMsg:@"获取数据失败"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)rechargeMoney {
    
    WeakSelf(self);
    [NetworkProgressHUD showHud];
    
    NSDictionary *params = [MNDSign signedParamWithDict:@{@"phone_num": self.bankModel.jxBankaccount.userAmountMobile,
                                                          @"recharge_money": self.rechargeMoneyTextField.text,
                                                          @"channel": @"app"}];
    [APIManager sendRequestWithPath:API_RECHARGE_MONEY parameters:params method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        NSLog(@"response: %@", responseModel.data);
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            MNDRechargeWebViewController *webVC = [[MNDRechargeWebViewController alloc] init];
            webVC.htmlString = responseModel.data;
            [weakself.navigationController pushViewController:webVC animated:YES];
            //短信充值
//            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:[MNDRechargeSMSViewController description] bundle:nil];
//            MNDRechargeSMSViewController *smsVC = [storyboard instantiateViewControllerWithIdentifier:[MNDRechargeSMSViewController description]];
//            smsVC.bankModel = weakself.bankModel;
//            smsVC.rechargeMoney = responseModel.data[@"recharge_money"];
//            if (weakself.isFromTender) {
//                smsVC.isFromTender = weakself.isFromTender;
//            }
//            [weakself.navigationController pushViewController:smsVC animated:YES];
        } else {
            
            NSDictionary *dict = responseModel.msg;
            if ([dict.allKeys containsObject:@"sign"]) {
                [NetworkProgressHUD hideHud];
                if ([responseModel.msg[@"sign"] isEqualToString:kOpenAccount] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSetPassword] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSignPayment] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSignAutoTender] ||
                    [responseModel.msg[@"sign"] isEqualToString:kSignAutoTransfer] ||
                    [responseModel.msg[@"sign"] isEqualToString:kRiskEvaluation] ||
                    [responseModel.msg[@"sign"] isEqualToString:kBandcard] ||
                    [responseModel.msg[@"sign"] isEqualToString:kExpiredSignPayment] ||
                    [responseModel.msg[@"sign"] isEqualToString:kExpiredAutotender]
                    ) {
                    [weakself showOpenDepositAlert:responseModel];
                }else {
                    [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
                }
            } else {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)showOpenDepositAlert:(ResponseModel *)response {
    NSString *signStr = response.msg[@"sign"];
    if ([signStr isEqualToString:kOpenAccount]) {
        
        [self showOpenAccountAlertWithModel:response];
        return;
    }
    
    __weak MNDOpenDeposAlertViewController *alertVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDeposAlertViewController description]];
    
    __weak UIView *alertView = alertVC.view;
    [KeyWindow addSubview:alertView];
    [self.tabBarController addChildViewController:alertVC];
    
    WeakSelf(self);
    
    [alertVC.confirmButton bk_addEventHandler:^(id sender) {
        [alertView removeFromSuperview];
        [alertVC removeFromParentViewController];
        
        [weakself toOpenDepositoryWithModel:response];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    alertVC.alertMessage = response.msg[@"error"];
    alertVC.alertType = response.msg[@"sign"];
}

- (void)showOpenAccountAlertWithModel:(ResponseModel *)response {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    __weak MNDDepositAlertViewController *alertVC = [storyboard instantiateViewControllerWithIdentifier:[MNDDepositAlertViewController description]];
    __weak UIView *springView = alertVC.view;
    [KeyWindow addSubview:springView];
    [self.tabBarController addChildViewController:alertVC];
    
    __weak typeof(self) weakSelf = self;
    
    [alertVC.depositBtn bk_addEventHandler:^(id sender) {
        [springView removeFromSuperview];
        [alertVC removeFromParentViewController];
        [weakSelf toOpenDepositoryWithModel:response];
        
    } forControlEvents:UIControlEventTouchUpInside];
    
    [alertVC.closeBtn bk_addEventHandler:^(id sender) {
        
        [UIView animateWithDuration:0.5 animations:^{
            alertVC.alertContainerView.frame = CGRectMake(alertVC.alertContainerView.frame.origin.x, kScreenHeight, alertVC.alertContainerView.frame.size.width, alertVC.alertContainerView.frame.size.height);
            alertVC.closeBtn.frame = CGRectMake(alertVC.closeBtn.frame.origin.x, kScreenHeight, alertVC.closeBtn.frame.size.width, alertVC.closeBtn.frame.size.height);
        } completion:^(BOOL finished) {
            [springView removeFromSuperview];
            [alertVC removeFromParentViewController];
        }];
    } forControlEvents:UIControlEventTouchUpInside];
}

- (void)toOpenDepositoryWithModel:(ResponseModel *)response {
    
    NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
    
    NSString *signStr = response.msg[@"sign"];
    //开通存管
    if ([signStr isEqualToString:kOpenAccount]) {
        MNDOpenDepositoryViewController *realVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryViewController description]];
        realVC.fromNaviIndex = index;
        
        [self.navigationController pushViewController:realVC animated:YES];
        
        return;
    }
    //设置交易密码
    if ([signStr isEqualToString:kSetPassword]) {
        
        [self loadPaymentPassword];
        return;
    }
    //设置缴费授权
    if ([signStr isEqualToString:kSignPayment] || [signStr isEqualToString:kExpiredSignPayment]) {
        MNDOpenTermsAuthViewController *openTermsAuthVC = [UIStoryboard viewControllerWithIdentifier:@"MNDOpenTermsAuthViewController"];
        openTermsAuthVC.fromNaviIndex = index;
        [self.navigationController pushViewController:openTermsAuthVC animated:YES];
        return;
//        MNDOpenDepositoryPaymentViewController *paymentVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryPaymentViewController description]];
//        paymentVC.fromNaviIndex = index;
//
//        [self.navigationController pushViewController:paymentVC animated:YES];
        
//        return;
    }
    //    //设置自动投标
    //    if ([signStr isEqualToString:kSignAutoTender] || [signStr isEqualToString:kExpiredAutotender]) {
    //
    //        MNDOpenDepositoryTenderViewController *tenderVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTenderViewController description]];
    //        if (self.userPhone.length > 0) {
    //            tenderVC.fromNaviIndex = index;
    //            tenderVC.phoneNumber = self.userPhone;
    //
    //            [self.navigationController pushViewController:tenderVC animated:YES];
    //        } else {
    //            [self loadUserPhone];
    //        }
    //        return;
    //    }
    //    //设置自动债转
    //    if ([signStr isEqualToString:kSignAutoTransfer]) {
    //
    //        MNDOpenDepositoryTransferViewController *transferVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryTransferViewController description]];
    //        if (self.userPhone.length > 0) {
    //            transferVC.fromNaviIndex = index;
    //            transferVC.phoneNumber = self.userPhone;
    //
    //            [self.navigationController pushViewController:transferVC animated:YES];
    //        } else {
    //            [self loadUserPhone];
    //        }
    //        return;
    //    }
}

/**
 设置交易密码
 */
- (void)loadPaymentPassword {
    
    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_DEPOSIT_SET_PASSWORD parameters:[MNDSign signedParamWithDict:@{@"channel": @"app"}] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            MNDDepositWebViewController *webVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositWebViewController description]];
            webVC.htmlStr = responseModel.data;
            webVC.title = @"设置交易密码";
            NSInteger index = [weakself.navigationController.viewControllers indexOfObject:weakself];
            webVC.fromNaviIndex = index;
            
            [weakself.navigationController pushViewController:webVC animated:YES];
        } else {
            [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)configBankInfo {
    
    self.userBalanceLabel.text = [NSString stringWithFormat:@"余额: %@", self.bankModel.userAmount.userAmountAvailable];
    self.rechargeMoneyTextField.placeholder = [NSString stringWithFormat:@"最低充值%@元", self.bankModel.rechargeLeastMoney];
    self.rechargeMoneyTextField.text = @"";
    
    if (self.bankModel.jxBankaccount.userAmountCardno.length <= 0) {
        self.bankLogoImageView.image = [UIImage imageNamed:@"bank_logo_placeholder"];
        self.bankLabel.text = @"您还未绑定银行卡";
        self.bankcardLabel.text = @"先绑卡再充值哦";
        [self.bindCardBtn setTitle:@"去添加" forState:UIControlStateNormal];
        [self.bindCardBtn setHidden:NO];
        return;
    }
    
    [self.bankLogoImageView sd_setImageWithURL: [NSURL URLWithString:self.bankModel.jxBankaccount.bank.banklogo] placeholderImage:[UIImage imageNamed:@"bank_logo_placeholder"]];
    
    [self.bindCardBtn setTitle:@"解绑" forState:UIControlStateNormal];
    
    if (self.bankModel.vc_quota_describe && self.bankModel.vc_quota_describe.length > 0) {
        self.bankLabel.text = [NSString stringWithFormat:@"%@(尾号%@)", self.bankModel.jxBankaccount.bank.bank, self.bankModel.jxBankaccount.lastNumber];
        self.bankcardLabel.text = self.bankModel.vc_quota_describe;
        
    } else {
        self.bankcardLabel.text = [NSString stringWithFormat:@"尾号%@", self.bankModel.jxBankaccount.lastNumber];
        self.bankLabel.text = self.bankModel.jxBankaccount.bank.bank;
    }
    
    if (self.bankModel.jxBankaccount.bank.bank.length <= 0) {
        self.cardNoConstraint.constant = -8;
    }
}

- (void)showSetPaymentPasswordAlert:(ResponseModel *)response {
    __weak MNDOpenDeposAlertViewController *alertVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDeposAlertViewController description]];

    __weak UIView *alertView = alertVC.view;
    [KeyWindow addSubview:alertView];
    [self.navigationController addChildViewController:alertVC];
    
    WeakSelf(self);
    
    [alertVC.confirmButton bk_addEventHandler:^(id sender) {
        [alertView removeFromSuperview];
        [alertVC removeFromParentViewController];
        [weakself loadPaymentPassword];
    } forControlEvents:UIControlEventTouchUpInside];
    
    [alertVC.closeButton bk_addEventHandler:^(id sender) {
        [alertView removeFromSuperview];
        [alertVC removeFromParentViewController];
        
    } forControlEvents:UIControlEventTouchUpInside];
    alertVC.alertMessage = response.msg[@"error"];
    alertVC.alertType = response.msg[@"sign"];
}

- (IBAction)bindCardAction:(id)sender {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Mine" bundle:nil];
    
    MNDBindBankcardViewController *bindcardVC = [storyboard instantiateViewControllerWithIdentifier:[MNDBindBankcardViewController description]];
    bindcardVC.bankModel = self.bankModel;
    
    [self.navigationController pushViewController:bindcardVC animated:YES];
}

- (IBAction)showBankcardDetailAction:(id)sender {
    
    if (self.bankModel.jxBankaccount.userAmountCardno.length <= 0) {
        
        [self bindCardAction:nil];
    }
//    MNDBankCardViewController *bankcardVC = [UIStoryboard viewControllerWithIdentifier:[MNDBankCardViewController description]];
//    bankcardVC.bankModel = self.bankModel;
//    bankcardVC.hideUnbindButton = YES;
//    [self.navigationController pushViewController:bankcardVC animated:YES];
}

- (void)toQuotaViewVC {
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Recharge" bundle:nil];
    
    MNDBaofuBankListViewController *bankListVC = [storyboard instantiateViewControllerWithIdentifier:[MNDBaofuBankListViewController description]];
    bankListVC.isQuota = YES;
    bankListVC.title = @"限额说明";
    [self.navigationController pushViewController:bankListVC animated:YES];
}

- (IBAction)rechargeAction:(id)sender {
    if (self.rechargeMoneyTextField.text.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入充值金额"];
        return;
    }
    
    NSDecimalNumber *rechargeMoney = [NSDecimalNumber decimalNumberWithString:self.rechargeMoneyTextField.text];
    
    if (!rechargeMoney) {
        [NetworkProgressHUD showHudMsg:@"您输入正确的金额"];
        return;
    }
    
    if (self.rechargeMoneyTextField.text.doubleValue < self.bankModel.rechargeLeastMoney.doubleValue) {
        NSString *msg = [NSString stringWithFormat:@"充值金额不能少于%@元", self.bankModel.rechargeLeastMoney];
        [NetworkProgressHUD showHudMsg:msg];
        return;
    }
    
    if (self.bankModel.jxBankaccount.userAmountCardno.length <= 0) {
//        [NetworkProgressHUD showHudMsg:@"充值前请先绑定银行卡哦"];
        [self bindCardAction:nil];
        return;
    }
    
    [self rechargeMoney];
}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    if ([segue.identifier isEqualToString:[MNDBaofuBindCardViewController description]]) {
        WeakSelf(self);
        
        UINavigationController *naviVC = segue.destinationViewController;
        MNDBaofuBindCardViewController *baofuVC = (MNDBaofuBindCardViewController *)naviVC.topViewController;
        baofuVC.bankModel = self.bankModel;
        baofuVC.bindCardResultBlock = ^(BOOL bindCardSuccess) {
            if (bindCardSuccess) {
                [weakself loadBankInfo];
            }
        };
    }
}


@end
